// 客流统计功能
class VisitorStatistics {
    constructor() {
        this.currentStats = null;
        this.historicalData = null;
        this.chart = null;
        this.updateInterval = null;
    }

    // 初始化统计看板
    async initialize() {
        await this.loadCurrentStatistics();
        await this.loadHistoricalData();
        this.initializeChart();
        this.setupEventListeners();
        this.startAutoUpdate();
    }

    // 加载当前统计数据
    async loadCurrentStatistics() {
        try {
            this.currentStats = await apiService.getCurrentVisitorStats();
            this.updateDashboard();
        } catch (error) {
            console.error('Failed to load current statistics:', error);
            this.loadMockCurrentStats();
        }
    }

    // 加载历史数据
    async loadHistoricalData(range = 'today') {
        try {
            this.historicalData = await apiService.getHistoricalVisitorStats();
            this.updateHistoricalDisplay();
            this.updateChart();
        } catch (error) {
            console.error('Failed to load historical data:', error);
            this.loadMockHistoricalData(range);
        }
    }

    // 更新仪表板
    updateDashboard() {
        if (!this.currentStats) return;

        // 更新实时入园人数
        const currentVisitorsElement = document.getElementById('currentVisitors');
        if (currentVisitorsElement) {
            currentVisitorsElement.textContent = this.currentStats.currentCount.toLocaleString();
        }

        // 更新趋势
        const trendElement = document.getElementById('visitorTrend');
        if (trendElement) {
            const trend = this.currentStats.trend || 0;
            trendElement.className = `trend ${trend >= 0 ? 'up' : 'down'}`;
            trendElement.textContent = `${trend >= 0 ? '↑' : '↓'} 较昨日 ${Math.abs(trend)}%`;
        }

        // 更新时间
        const updateTimeElement = document.getElementById('visitorUpdateTime');
        if (updateTimeElement) {
            updateTimeElement.textContent = Utils.formatTime(new Date());
        }

        // 更新统计卡片
        this.updateStatCards();
    }

    // 更新统计卡片
    updateStatCards() {
        const statsContainer = document.querySelector('.stats-container');
        if (!statsContainer || !this.currentStats) return;

        statsContainer.innerHTML = `
            <div class="stat-card">
                <div class="stat-value">${this.currentStats.todayEntered?.toLocaleString() || '0'}</div>
                <div class="stat-label">今日入园</div>
            </div>
            <div class="stat-card">
                <div class="stat-value">${this.currentStats.currentCount?.toLocaleString() || '0'}</div>
                <div class="stat-label">当前在园</div>
            </div>
            <div class="stat-card">
                <div class="stat-value">${this.currentStats.todayExited?.toLocaleString() || '0'}</div>
                <div class="stat-label">今日出园</div>
            </div>
            <div class="stat-card">
                <div class="stat-value">${this.currentStats.peakCount?.toLocaleString() || '0'}</div>
                <div class="stat-label">今日峰值</div>
            </div>
        `;
    }

    // 初始化图表
    initializeChart() {
        const canvas = document.getElementById('trendCanvas');
        if (!canvas) return;

        const ctx = canvas.getContext('2d');
        
        // 简单的Canvas图表绘制
        this.drawSimpleChart(ctx);
    }

    // 绘制简单图表
    drawSimpleChart(ctx) {
        const width = ctx.canvas.width;
        const height = ctx.canvas.height;
        const padding = 20;

        // 清除画布
        ctx.clearRect(0, 0, width, height);

        // 绘制坐标轴
        ctx.strokeStyle = '#ddd';
        ctx.lineWidth = 1;
        ctx.beginPath();
        ctx.moveTo(padding, padding);
        ctx.lineTo(padding, height - padding);
        ctx.lineTo(width - padding, height - padding);
        ctx.stroke();

        // 如果有数据，绘制折线
        if (this.historicalData && this.historicalData.hourly) {
            const data = this.historicalData.hourly;
            const maxValue = Math.max(...data.map(d => d.count));
            
            ctx.strokeStyle = '#A375FF';
            ctx.lineWidth = 2;
            ctx.beginPath();

            data.forEach((point, index) => {
                const x = padding + (index / (data.length - 1)) * (width - 2 * padding);
                const y = height - padding - (point.count / maxValue) * (height - 2 * padding);
                
                if (index === 0) {
                    ctx.moveTo(x, y);
                } else {
                    ctx.lineTo(x, y);
                }
            });

            ctx.stroke();

            // 绘制数据点
            ctx.fillStyle = '#A375FF';
            data.forEach((point, index) => {
                const x = padding + (index / (data.length - 1)) * (width - 2 * padding);
                const y = height - padding - (point.count / maxValue) * (height - 2 * padding);
                
                ctx.beginPath();
                ctx.arc(x, y, 3, 0, 2 * Math.PI);
                ctx.fill();
            });
        } else {
            // 没有数据时显示提示
            ctx.fillStyle = '#666';
            ctx.font = '14px Arial';
            ctx.textAlign = 'center';
            ctx.fillText('暂无数据', width / 2, height / 2);
        }
    }

    // 更新图表
    updateChart() {
        const canvas = document.getElementById('trendCanvas');
        if (canvas) {
            const ctx = canvas.getContext('2d');
            this.drawSimpleChart(ctx);
        }
    }

    // 更新历史数据显示
    updateHistoricalDisplay() {
        const timeStatsContainer = document.getElementById('timeStats');
        if (!timeStatsContainer || !this.historicalData) return;

        if (this.historicalData.timeStats) {
            timeStatsContainer.innerHTML = this.historicalData.timeStats.map(stat => `
                <div class="time-stat-item">
                    <span class="time-range">${stat.period}</span>
                    <span class="visitor-count">${stat.count.toLocaleString()}人</span>
                    <span class="percentage">${stat.percentage}%</span>
                </div>
            `).join('');
        }
    }

    // 更新时间范围
    updateTimeRange() {
        const timeRangeSelect = document.getElementById('timeRange');
        if (timeRangeSelect) {
            const range = timeRangeSelect.value;
            this.loadHistoricalData(range);
        }
    }

    // 显示时间筛选器
    showTimeFilter() {
        // 实际开发中这里可以显示更复杂的时间筛选器
        Utils.showNotification('时间筛选功能开发中', 'info');
    }

    // 设置事件监听器
    setupEventListeners() {
        // 时间范围选择
        const timeRangeSelect = document.getElementById('timeRange');
        if (timeRangeSelect) {
            timeRangeSelect.addEventListener('change', () => this.updateTimeRange());
        }

        // 筛选按钮
        const filterBtn = document.querySelector('.btn-filter');
        if (filterBtn) {
            filterBtn.addEventListener('click', () => this.showTimeFilter());
        }

        // 窗口大小变化时重绘图表
        window.addEventListener('resize', Utils.debounce(() => {
            this.updateChart();
        }, 250));
    }

    // 开始自动更新
    startAutoUpdate() {
        this.updateInterval = setInterval(async () => {
            await this.loadCurrentStatistics();
            console.log('Visitor statistics updated');
        }, 30000); // 30秒更新一次
    }

    // 停止自动更新
    stopAutoUpdate() {
        if (this.updateInterval) {
            clearInterval(this.updateInterval);
        }
    }

    // 导出数据
    exportData() {
        if (!this.currentStats || !this.historicalData) {
            Utils.showNotification('暂无数据可导出', 'warning');
            return;
        }

        const data = {
            currentStats: this.currentStats,
            historicalData: this.historicalData,
            exportTime: new Date().toISOString()
        };

        const dataStr = JSON.stringify(data, null, 2);
        const dataBlob = new Blob([dataStr], { type: 'application/json' });
        
        const link = document.createElement('a');
        link.href = URL.createObjectURL(dataBlob);
        link.download = `visitor-statistics-${Utils.formatDate(new Date())}.json`;
        link.click();
        
        Utils.showNotification('数据导出成功', 'success');
    }

    // 模拟数据（开发用）
    loadMockCurrentStats() {
        this.currentStats = {
            currentCount: 1245,
            todayEntered: 2856,
            todayExited: 1611,
            peakCount: 1560,
            trend: 15.2
        };
        this.updateDashboard();
    }

    loadMockHistoricalData(range) {
        const baseData = [
            { hour: '08:00', count: 120 },
            { hour: '09:00', count: 450 },
            { hour: '10:00', count: 890 },
            { hour: '11:00', count: 1120 },
            { hour: '12:00', count: 980 },
            { hour: '13:00', count: 1050 },
            { hour: '14:00', count: 1340 },
            { hour: '15:00', count: 1560 },
            { hour: '16:00', count: 1420 },
            { hour: '17:00', count: 1180 },
            { hour: '18:00', count: 950 },
            { hour: '19:00', count: 620 }
        ];

        this.historicalData = {
            range: range,
            hourly: baseData,
            timeStats: [
                { period: '上午 (08:00-12:00)', count: 2670, percentage: 42 },
                { period: '中午 (12:00-14:00)', count: 2030, percentage: 32 },
                { period: '下午 (14:00-18:00)', count: 1650, percentage: 26 }
            ]
        };

        this.updateHistoricalDisplay();
        this.updateChart();
    }
}

// 创建全局实例
const visitorStatistics = new VisitorStatistics();

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 只在首页初始化客流统计
    if (window.location.pathname.endsWith('index.html') || 
        window.location.pathname === '/' || 
        window.location.pathname.endsWith('/')) {
        visitorStatistics.initialize();
    }
});

// 页面卸载时清理
window.addEventListener('beforeunload', function() {
    visitorStatistics.stopAutoUpdate();
});

// 导出到全局作用域
window.visitorStatistics = visitorStatistics;
window.updateTimeRange = () => visitorStatistics.updateTimeRange();
window.showTimeFilter = () => visitorStatistics.showTimeFilter();